package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.douwong.student.R;
import com.douwong.student.adapter.ClassFileRecordAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseFragment;
import com.douwong.student.contant.CommonConfig;
import com.douwong.student.interfaces.WorkResultNotify;
import com.douwong.student.model.ClassFileRecordBean;
import com.douwong.student.model.ClassNoteItem;
import com.douwong.student.model.RequestAction;
import com.douwong.student.popuwindow.UpLoadPopuWindow;
import com.douwong.student.task.ClassFileRecordTask;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.view.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;


/**
 * yichao
 * 2017 6.28
 */
@SuppressLint("ValidFragment")
public abstract class ClassFileRecordFragment extends BaseFragment {

    private PullToRefreshListView list_view;
    private ClassFileRecordAdapter adapter;
    private View view;
    private int visibleLastIndex = 0, currentPageIndex = 1;
    private BaseApplication app;
    private boolean isRefreshing = false;
    private String startTime = null;
    private String endTime = null;
    private String fileType;
    private String subjectId = null;
    private ImageView statue_img;
    private UpLoadPopuWindow popu;
    private boolean isFirst = true;
    private ClassFileRecordTask mTask;
    private final int SHOW_POPUWINDOW = 2002;
    private final int DISS_POPUWINDOW = 2003;
    private Context mContext;
    private List<ClassFileRecordBean> mDataList;
    /**
     * 文件类型   1为白板2为课堂笔记
     *
     * @return
     */
    protected abstract String getFileType();

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;

    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == SHOW_POPUWINDOW) {
                popu.showAtLocation(view, Gravity.CENTER, 0, 0);
                popu.setText("加载中...");
                loadData(RequestAction.INIT, 1, false);
            } else if (msg.what == DISS_POPUWINDOW) {
                if (popu != null && popu.isShowing()) {
                    popu.dismiss();
                }
            }
        }


    };
    BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(CommonConfig.CLASSFILE_SEARCH)) {
                startTime = intent.getStringExtra("start_time");
                endTime = intent.getStringExtra("end_time");
                subjectId = intent.getStringExtra("subjectId");

            }
        }
    };
    IntentFilter filter = new IntentFilter() {
        {
            addAction(CommonConfig.CLASSFILE_SEARCH);
        }
    };

    @Override
    protected View getRootView(LayoutInflater inflater, ViewGroup container) {

        view = LayoutInflater.from(getActivity()).inflate(R.layout.black_board, null);
        list_view = (PullToRefreshListView) view.findViewById(R.id.class_file_listview);
        statue_img = (ImageView) view.findViewById(R.id.statue_img);
        return view;
    }

    @Override
    protected void initData() {
        super.initData();
        popu = new UpLoadPopuWindow(mContext);
        getActivity().registerReceiver(receiver, filter);
        mDataList = new ArrayList<>();
        adapter = new ClassFileRecordAdapter(mDataList, getActivity());
        list_view.setAdapter(adapter);
        app = (BaseApplication) getActivity().getApplication();
        fileType = getFileType();//1，课堂笔记 2，小黑板
        if (fileType.equals("2")) {
            handler.sendEmptyMessageDelayed(SHOW_POPUWINDOW, 500);
        } else {
            loadData(RequestAction.INIT, 1, false);
        }
    }

    @Override
    protected void initEvent() {
        list_view.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                currentPageIndex=1;
                loadData(RequestAction.REFRESH, currentPageIndex, false);
            }
        });


        list_view.setOnILoadMoreListener(new PullToRefreshListView.OnILoadMoreListener() {
            @Override
            public void onLoadMore() {

                if (isRefreshing) {
                    return;
                }
                isRefreshing = true;
                ++currentPageIndex;
                loadData(RequestAction.LOADMROE, currentPageIndex, false);


            }
        });

    }


    /**
     * 加载数据
     *
     * @param action
     * @param pageIndex
     * @param isSearch
     */
    private void loadData(final RequestAction action, int pageIndex, boolean isSearch) {

        mTask = new ClassFileRecordTask(isSearch, action, new WorkResultNotify<ClassNoteItem>() {

            @Override
            public void notify(int stateCode, List<ClassNoteItem> arryResult) {
                if (popu != null && popu.isShowing()) {
                    handler.sendEmptyMessage(DISS_POPUWINDOW);
                }
                if (action == RequestAction.INIT) {
                    if (stateCode == ClassFileRecordTask.REQUESTOK) {
                        //成功
                        LoadSuccessList(arryResult);

                    //    adapter.setData(mDataList);
                        adapter.notifyDataSetChanged();
                    }else if (stateCode== ClassFileRecordTask.NO_NETWOK){
                        ToastUtils.makeText(mContext,"请检查网络");
                    }


                } else if (action == RequestAction.REFRESH) {

                    if (stateCode== ClassFileRecordTask.NO_NETWOK){

                        ToastUtils.makeText(mContext,"请检查网络");
                        mDataList.clear();
                        adapter.setData(mDataList);
                        list_view.onRefreshComplete();
                        adapter.notifyDataSetChanged();

                    }else if (stateCode==ClassFileRecordTask.NO_DATA){
                        mDataList.clear();
                        adapter.setData(mDataList);
                        list_view.onRefreshComplete();
                        adapter.notifyDataSetChanged();

                    }else if (stateCode==ClassFileRecordTask.REQUESTOK){
                        mDataList.clear();
                      //  mDataList.addAll(arryResult);
                        LoadSuccessList(arryResult);
                        adapter.setData(mDataList);
                        list_view.onRefreshComplete();
                        adapter.notifyDataSetChanged();

                    }


                } else if (action == RequestAction.LOADMROE) {
                    isRefreshing=false;
                    if (stateCode== ClassFileRecordTask.NO_NETWOK){
                        --currentPageIndex;
                        ToastUtils.makeText(mContext,"请检查网络");
                        list_view.completeLoadMore();
                        adapter.notifyDataSetChanged();

                    }else if (stateCode==ClassFileRecordTask.NO_DATA){
                        --currentPageIndex;
                        list_view.completeLoadMore();
                        adapter.notifyDataSetChanged();
                        ToastUtils.makeText(mContext,"没有更多数据了");

                    }else if (stateCode==ClassFileRecordTask.REQUESTOK){
                        LoadSuccessList(arryResult);
                      //  mDataList.addAll(arryResult);
                        list_view.completeLoadMore();
                        adapter.notifyDataSetChanged();

                    }
                }


            }
        }, app);
        mTask.executeOnExecutor(Executors.newCachedThreadPool(), fileType, subjectId, startTime, pageIndex + "");

    }

    /**
     * 获取网络数据成功
     * @param arryResult
     */
    private void LoadSuccessList(List<ClassNoteItem> arryResult) {
        for (int i = 0; i < arryResult.size(); i++) {

            ClassFileRecordBean bean = new ClassFileRecordBean();
            String time = arryResult.get(i).getCreate_time().substring(0, 10);
            bean.setCreateTime(time);
            bean.getList().add(arryResult.get(i));
            for (int j = i + 1; j < arryResult.size(); j++) {
                String temp = arryResult.get(j).getCreate_time().substring(0, 10);
                if (time.equals(temp)) {
                    bean.getList().add(arryResult.get(j));
                }
            }
            if (i == 0) {
                mDataList.add(bean);
            } else {
                boolean isExit = false;
                for (int k = 0; k < mDataList.size(); k++) {
                    if (bean.getCreateTime().equals(mDataList.get(k).getCreateTime())) {
                        isExit = true;
                    }
                }
                if (!isExit) {
                    mDataList.add(bean);
                }
            }


        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().unregisterReceiver(receiver);

        if (popu != null && popu.isShowing()) {
            popu.dismiss();
        }
        if (mTask != null && !mTask.isCancelled()) {
            mTask.cancel(true);
        }


    }

}
